<template>
    <a-spin :spinning="confirmLoading">
        <j-form-container :disabled="formDisabled">
            <a-form :form="form" slot="detail">
                <a-row>
                    <a-col :span="24">
                        <a-form-item label="进口编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['entryNumber']" placeholder="请输入进口编号"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="进厂道闸" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['barrierGate', validatorRules.barrierGate]"
                                placeholder="请输入进厂道闸"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="出口编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['exitNumber']" placeholder="请输入出口编号"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="出厂道闸" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['barrierGate1']" placeholder="请输入出厂道闸"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="进厂时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-date placeholder="请选择进厂时间"
                                v-decorator="['entryTime', validatorRules.entryTime]"
                                :trigger-change="true" :show-time="true"
                                date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="出厂时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-date placeholder="请选择出厂时间"
                                v-decorator="['exitTime', validatorRules.exitTime]"
                                :trigger-change="true" :show-time="true"
                                date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="车牌号码" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['plateNo', validatorRules.plateNo]"
                                placeholder="请输入车牌号码"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="号牌颜色" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-dict-select-tag type="radio"
                                v-decorator="['plateColor', validatorRules.plateColor]"
                                :trigger-change="true" dictCode="cpys" placeholder="请选择号牌颜色" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="车辆类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-dict-select-tag type="list" v-decorator="['carType']"
                                :trigger-change="true" dictCode="cllx" placeholder="请选择车辆类型" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="注册登记日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-date placeholder="请选择注册登记日期" v-decorator="['registrationTime']"
                                :trigger-change="true" :show-time="true"
                                date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="车辆识别代码(VIN)" :labelCol="labelCol"
                            :wrapperCol="wrapperCol">
                            <a-input v-decorator="['vin', validatorRules.vin]"
                                placeholder="请输入车辆识别代码(VIN)"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="车辆品牌型号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['carBrandModel']"
                                placeholder="请输入车辆品牌型号"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="燃料类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-dict-select-tag type="list" v-decorator="['fuelType']"
                                :trigger-change="true" dictCode="fuel_type" placeholder="请选择燃料类型" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="排放标准" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-dict-select-tag type="list"
                                v-decorator="['evnType', validatorRules.evnType]"
                                :trigger-change="true" dictCode="pflx" placeholder="请选择排放标准" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="联网状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-dict-select-tag type="list" v-decorator="['networkingStatus']"
                                :trigger-change="true" dictCode="networking_status"
                                placeholder="请选择联网状态" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="使用性质" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-dict-select-tag type="list" v-decorator="['function']"
                                :trigger-change="true" dictCode="function" placeholder="请选择使用性质" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="进厂运输货物名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['inTransportGoodsName']"
                                placeholder="请输入进厂运输货物名称"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="进厂运输量" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['inFreightVolume']"
                                placeholder="请输入进厂运输量"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="出厂运输货物名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['outTransportGoodsName']"
                                placeholder="请输入出厂运输货物名称"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="出厂运输量" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['outFreightVolume']"
                                placeholder="请输入出厂运输量"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="车队名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['fleetName']" placeholder="请输入车队名称"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="进厂照片" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-image-upload isMultiple
                                v-decorator="['entryPic', validatorRules.entryPic]"></j-image-upload>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="出厂照片" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-image-upload isMultiple
                                v-decorator="['exitPic', validatorRules.exitPic]"></j-image-upload>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="随车清单" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-image-upload isMultiple
                                v-decorator="['inventory', validatorRules.inventory]"></j-image-upload>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="行驶证" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-image-upload isMultiple
                                v-decorator="['lisense', validatorRules.lisense]"></j-image-upload>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="进厂视频" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-upload v-decorator="['entryVideo']" name="file" :multiple="true"
                                :action="uploadAction" list-type="picture-card" :headers="headers"
                                :data="{ 'isup': 1, 'bizPath': bizPath }" :fileList="fileList1"
                                :beforeUpload="beforeUpload" @preview="handlePreview1"
                                @change="handleChange1" :disabled="disabled">
                                <div v-if="fileList1.length < 8">
                                    <a-icon type="plus" />
                                    <div class="ant-upload-text">
                                        上传
                                    </div>
                                </div>
                            </a-upload>
                            <a-modal :visible="previewVisible1" :footer="null"
                                @cancel="handleVideoCancel1">
                                <video alt="example" style="width: 100%" :src="previewSrc1"
                                    controls>
                                </video>
                            </a-modal>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="出厂视频" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-upload v-decorator="['exitVideo']" name="file" :multiple="true"
                                :action="uploadAction" list-type="picture-card" :headers="headers"
                                :data="{ 'isup': 1, 'bizPath': bizPath }" :fileList="fileList"
                                :beforeUpload="beforeUpload" @preview="handlePreview"
                                @change="handleChange" :disabled="disabled">
                                <div v-if="fileList.length < 8">
                                    <a-icon type="plus" />
                                    <div class="ant-upload-text">
                                        上传
                                    </div>
                                </div>
                            </a-upload>
                            <a-modal :visible="previewVisible" :footer="null"
                                @cancel="handleVideoCancel">
                                <video alt="example" style="width: 100%" :src="previewSrc" controls>
                                </video>
                            </a-modal>
                        </a-form-item>
                    </a-col>
                    <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
                        <a-button @click="submitForm">提 交</a-button>
                    </a-col>
                </a-row>
            </a-form>
        </j-form-container>
    </a-spin>
</template>

<script>

import { httpAction, getAction, postAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
const FILE_TYPE_ALL = "all"
const FILE_TYPE_IMG = "image"
const FILE_TYPE_MP4 = "video/mp4"
const FILE_TYPE_TXT = "file"
const uidGenerator = () => {
    return '-' + parseInt(Math.random() * 10000 + 1, 10);
}
const getFileName = (path) => {
    if (path.lastIndexOf("\\") >= 0) {
        let reg = new RegExp("\\\\", "g");
        path = path.replace(reg, "/");
    }
    return path.substring(path.lastIndexOf("/") + 1);
}
export default {
    name: 'CarRecordForm',
    components: {
    },
    props: {
        text: {
            type: String,
            required: false,
            default: "点击上传"
        },
        fileType: {
            type: String,
            required: false,
            default: FILE_TYPE_ALL
        },
        /*这个属性用于控制文件上传的业务路径*/
        bizPath: {
            type: String,
            required: false,
            default: "temp"
        },
        value: {
            type: [String, Array],
            required: false
        },
        disabled: {
            type: Boolean,
            required: false,
            default: false
        },
        //流程表单data
        formData: {
            type: Object,
            default: () => { },
            required: false
        },
        //表单模式：true流程表单 false普通表单
        formBpm: {
            type: Boolean,
            default: false,
            required: false
        },
        //表单禁用
        disabled: {
            type: Boolean,
            default: false,
            required: false
        }
    },
    data() {
        return {
            handleDeleteValues: 0,
            handleDeleteValues1: 0,
            uploadAction: window._CONFIG['domianURL'] + "/sys/common/upload",//图片上传地址
            imgErver: window._CONFIG['domianURL'] + '/sys/common/play',//图片预览地址/sys/common/view
            videoErver: window._CONFIG['domianURL'] + 'sys/common/view_video',//视频预览地址
            isCreatFile: true,//是否创建文件占位dom
            headers: {},
            fileList: [],
            fileList1: [],
            previewSrc: '',
            previewSrc1: '',
            previewVisible: false,
            previewVisible1: false,
            form: this.$form.createForm(this),
            model: {},
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
            confirmLoading: false,
            validatorRules: {
                plateNo: {
                    rules: [
                        { required: true, message: '请输入车牌号码!' },
                    ]
                },
                plateColor: {
                    rules: [
                        { required: true, message: '请输入号牌颜色!' },
                    ]
                },
                entryTime: {
                    rules: [
                        { required: true, message: '请输入进厂时间!' },
                    ]
                },
                barrierGate: {
                    rules: [
                        { required: true, message: '请输入进厂道闸!' },
                    ]
                },
                entryPic: {
                    rules: [
                        { required: true, message: '请输入进厂照片!' },
                    ]
                },
                exitTime: {
                    rules: [
                        { required: true, message: '请输入出厂时间!' },
                    ]
                },
                exitPic: {
                    rules: [
                        { required: true, message: '请输入出厂照片!' },
                    ]
                },
                vin: {
                    rules: [
                        { required: true, message: '请输入车辆识别代码(VIN)!' },
                    ]
                },
                evnType: {
                    rules: [
                        { required: true, message: '请输入排放标准!' },
                    ]
                },
                inventory: {
                    rules: [
                        { required: true, message: '请输入随车清单!' },
                    ]
                },
                lisense: {
                    rules: [
                        { required: true, message: '请输入行驶证!' },
                    ]
                },
                engineNum: {
                    rules: [
                        { required: true, message: '请输入发动机编号!' },
                    ]
                },
            },
            url: {
                add: "/carinfo/carRecord/add",
                edit: "/carinfo/carRecord/edit",
                queryById: "/carinfo/carRecord/queryById",
                upload: "/sys/common/upload",
            }
        }
    },
    computed: {
        formDisabled() {
            if (this.formBpm === true) {
                if (this.formData.disabled === false) {
                    return false
                }
                return true
            }
            return this.disabled
        },
        showFlowSubmitButton() {
            if (this.formBpm === true) {
                if (this.formData.disabled === false) {
                    return true
                }
            }
            return false
        }
    },
    created() {
        const token = Vue.ls.get(ACCESS_TOKEN);
        this.headers = { "X-Access-Token": token }
        //如果是流程中表单，则需要加载流程表单data
        this.showFlowData();
    },
    methods: {
        handlePathChange() {
            let uploadFiles = this.fileList
            let path = ''
            if (!uploadFiles || uploadFiles.length == 0) {
                path = ''
            }
            let arr = [];

            for (var a = 0; a < uploadFiles.length; a++) {
                if (uploadFiles[a].response) {
                    arr.push(uploadFiles[a].response.message)
                }
            }
            if (arr.length > 0) {
                path = arr.join(",")
            }
            this.$emit('change', path);
        },
        handlePathChange1() {
            let uploadFiles = this.fileList1
            let path = ''
            if (!uploadFiles || uploadFiles.length == 0) {
                path = ''
            }
            let arr = [];

            for (var a = 0; a < uploadFiles.length; a++) {
                if (uploadFiles[a].response) {
                    arr.push(uploadFiles[a].response.message)
                }
            }
            if (arr.length > 0) {
                path = arr.join(",")
            }
            this.$emit('change', path);
        },
        beforeUpload(file) {//上传文件前对文件类型判断
            var fileType = file.type;
            if (fileType.indexOf('mp4') < 0) {
                this.$message.warning('请上传mp4文件');
                this.isCreatFile = false;
                return false;
            }
            //TODO 扩展功能验证文件大小
        },
        handleChange(info) {
            if (this.isCreatFile == false) {
                return false
            }
            let fileList = info.fileList
            if (info.file.status === 'done') {
                if (info.file.response.success) {
                    fileList = fileList.map((file) => {
                        if (file.response) {
                            file.url = this.urlDownload + file.response.message;
                        }
                        return file;
                    });
                }
                this.handleDeleteValues = 0;
                this.$message.success(`${info.file.name} 上传成功!`);
            } else if (info.file.status === 'error') {
                this.$message.error(`${info.file.name} 上传失败.`);
            } else if (info.file.status === 'removed') {
                this.handleDelete(info.file)
            }
            this.fileList = fileList
            if (info.file.status === 'done' || info.file.status === 'removed') {
                this.handlePathChange()
            }
        },
        handleChange1(info) {
            if (this.isCreatFile == false) {
                return false
            }
            let fileList1 = info.fileList
            if (info.file.status === 'done') {
                if (info.file.response.success) {
                    fileList1 = fileList1.map((file) => {
                        if (file.response) {
                            file.url = this.urlDownload + file.response.message;
                        }
                        return file;
                    });
                }
                this.handleDeleteValues1 = 0;
                this.$message.success(`${info.file.name} 上传成功!`);
            } else if (info.file.status === 'error') {
                this.$message.error(`${info.file.name} 上传失败.`);
            } else if (info.file.status === 'removed') {
                this.handleDelete1(info.file)
            }
            this.fileList1 = fileList1
            if (info.file.status === 'done' || info.file.status === 'removed') {
                this.handlePathChange1()
            }
        },
        handleVideoCancel() {
            this.previewVisible = false;
            let myVideo = document.getElementsByTagName('video');
            let arr = Array.from(myVideo)
            arr.forEach(item => {//关闭时暂停播放
                item.pause()
            })
        },
        handleVideoCancel1() {
            this.previewVisible1 = false;
            let myVideo = document.getElementsByTagName('video');
            let arr = Array.from(myVideo)
            arr.forEach(item => {//关闭时暂停播放
                item.pause()
            })
        },
        async handlePreview(file) {//判断打开不同文件预览窗口
            console.log("~~~model打开~~~", file.type);
            var fileType = file.type;
            if (fileType == 'video/mp4') {
                if (file.response.message.substring(0, 4) == 'http') {
                    this.previewSrc = file.response.message;
                } else {
                    this.previewSrc = this.imgErver + '/' + file.response.message;
                }
                this.previewVisible = true;
            }
        },
        async handlePreview1(file) {//判断打开不同文件预览窗口
            console.log("~~~model打开~~~", file.type);
            var fileType = file.type;
            if (fileType == 'video/mp4') {
                if (file.response.message.substring(0, 4) == 'http') {
                    this.previewSrc1 = file.response.message;
                } else {
                    this.previewSrc1 = this.imgErver + '/' + file.response.message;
                }
                this.previewVisible1 = true;
            }
        },
        handleDelete(file) {
            //如有需要新增 删除逻辑
            console.log(file)
            this.handleDeleteValues = 1;
        },
        handleDelete1(file) {
            //如有需要新增 删除逻辑
            console.log(file);
            this.handleDeleteValues1 = 1;
        },
        add() {
            this.edit({});
        },
        edit(record) {
            console.log(record)
            this.form.resetFields();
            this.model = Object.assign({}, record);
            this.visible = true;
            this.$nextTick(() => {
                this.form.setFieldsValue(pick(this.model, 'plateNo', 'plateColor', 'entryTime', 'barrierGate', 'entryPic', 'entryNumber', 'exitTime', 'barrierGate1', 'exitPic', 'exitNumber', 'carType', 'registrationTime', 'vin', 'carBrandModel', 'fuelType', 'evnType', 'networkingStatus', 'function', 'inTransportGoodsName', 'inFreightVolume', 'outTransportGoodsName', 'outFreightVolume', 'fleetName', 'inventory', 'lisense', 'registrationCode', 'producedTime', 'vehicleOwner', 'machineryType', 'pin', 'mechanicalModel', 'engineModel', 'engineProducer', 'engineNum', 'machineNameplate', 'engineNameplate', 'machineLabel', 'whiteList', 'status', 'carSort', 'entryVideo', 'exitVideo'))
                if (this.model.exitVideo != null && this.model.exitVideo != "") {
                    this.fileList = [
                        {
                            uid: '001',
                            name: this.model.exitVideo,
                            status: 'done',
                            url: this.model.exitVideo,
                            type: 'video/mp4',
                            response: { message: this.model.exitVideo },
                        }
                    ];
                }
                if (this.model.entryVideo != null && this.model.entryVideo != "") {
                    this.fileList1 = [
                        {
                            uid: '002',
                            name: this.model.entryVideo,
                            status: 'done',
                            url: this.model.entryVideo,
                            type: 'video/mp4',
                            response: { message: this.model.entryVideo },
                        }
                    ];
                }
            })
        },
        //渲染流程表单数据
        showFlowData() {
            if (this.formBpm === true) {
                let params = { id: this.formData.dataId };
                getAction(this.url.queryById, params).then((res) => {
                    if (res.success) {
                        this.edit(res.result);
                    }
                });
            }
        },
        submitForm() {
            const that = this;
            // 触发表单验证
            this.form.validateFields((err, values) => {
                if (!err) {
                    that.confirmLoading = true;
                    let httpurl = '';
                    let method = '';
                    if (!this.model.id) {
                        httpurl += this.url.add;
                        method = 'post';
                    } else {
                        httpurl += this.url.edit;
                        method = 'put';
                    }
                    let formData = Object.assign(this.model, values);
                    if (method == 'post') {
                        if (this.model.entryVideo) {
                            formData.entryVideo = formData.entryVideo.file.response.message;
                        } else {
                            formData.entryVideo = "";
                        }
                        if (this.model.exitVideo) {
                            formData.exitVideo = formData.exitVideo.file.response.message;
                        } else {
                            formData.exitVideo = "";
                        }
                        if (!this.model.carSort) {
                            formData.carSort = 0;
                        }
                    } else {
                        const entryVideoValue = this.form.getFieldValue('entryVideo');
                        const exitVideoValue = this.form.getFieldValue('exitVideo');
                        if (typeof entryVideoValue === 'object') {
                            formData.entryVideo = entryVideoValue.file.response.message;
                        }
                        if (typeof exitVideoValue === 'object') {
                            formData.exitVideo = exitVideoValue.file.response.message;
                        }
                    }
                    if (this.handleDeleteValues === 1) {
                        formData.exitVideo = "";
                    }
                    if (this.handleDeleteValues1 === 1) {
                        formData.entryVideo = "";
                    }
                    console.log("表单提交数据", formData)
                    httpAction(httpurl, formData, method).then((res) => {
                        if (res.success) {
                            that.$message.success(res.message);
                            that.$emit('ok');
                        } else {
                            that.$message.warning(res.message);
                        }
                    }).finally(() => {
                        that.confirmLoading = false;
                    })
                }

            })
        },
        popupCallback(row) {
            this.form.setFieldsValue(pick(row, 'plateNo', 'plateColor', 'entryTime', 'barrierGate', 'entryPic', 'entryNumber', 'exitTime', 'barrierGate1', 'exitPic', 'exitNumber', 'carType', 'registrationTime', 'vin', 'carBrandModel', 'fuelType', 'evnType', 'networkingStatus', 'function', 'inTransportGoodsName', 'inFreightVolume', 'outTransportGoodsName', 'outFreightVolume', 'fleetName', 'inventory', 'lisense', 'registrationCode', 'producedTime', 'vehicleOwner', 'machineryType', 'pin', 'mechanicalModel', 'engineModel', 'engineProducer', 'engineNum', 'machineNameplate', 'engineNameplate', 'machineLabel', 'whiteList', 'status', 'carSort', 'entryVideo', 'exitVideo'))
        },
    },
    model: {
        prop: 'value',
        event: 'change'
    },
}

</script>